﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace CommonModel
{
    public class Result<T>
    {
        public Result()
        {
            Success = true;
            Message = "操作成功！";
        }
        public Result(bool succ, string msg = "操作成功!", int error = 0)
        {
            this.Success = succ;
            this.Message = msg;
            this.ErrorCode = error;
        }

        public Result(OperateException oe)
        {
            this.Success = false;
            this.Message = oe.Message;
            this.ErrorCode = oe.ErrorCode;
        }
        public bool Success { get; set; }
        public string Message { get; set; }

        public T Value { get; set; }
        public int ErrorCode { get; set; }
        /// <summary>
        /// 序列化成Json
        /// </summary>
        /// <returns></returns>
        public string ToJson()
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            return JsonConvert.SerializeObject(new { success = this.Success, message = this.Message, errorcode = this.ErrorCode, value = this.Value }, Newtonsoft.Json.Formatting.Indented, timeFormat);
        }
        /// <summary>
        /// 序列化成Json
        /// </summary>
        /// <returns></returns>
        public string Serialize()
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            return JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented, timeFormat);
        }

        public static Result SuccessResult = new Result(true);

    }
    public class Result : Result<object>
    {
        public Result() : base() { }

        public Result(bool succ, string msg = "操作成功!", int error = 0)
            : base(succ, msg, error)
        {

        }
        public Result(OperateException oe)
            : base(oe)
        {

        }

    }
}
